package com.lin.java.tool.oss.storage.engine.local;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.lin.java.tool.general.enums.OssEnum;
import com.lin.java.tool.general.ex.CustomFileException;
import com.lin.java.tool.oss.model.UploadFileData;
import com.lin.java.tool.oss.model.dto.DownloadRespDTO;
import com.lin.java.tool.oss.model.dto.UploadRespDTO;
import com.lin.java.tool.oss.storage.StorageEngine;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author linjiang
 * @date 2024/7/26
 * @fn
 */
@Slf4j
public class LocalStorageEngine implements StorageEngine {

    private String bucket;

    public LocalStorageEngine(String bucket) {
        this.bucket = bucket;
    }

    @Override
    public UploadRespDTO put(UploadFileData uploadFileData) {
        log.info("本地文件上传。。。。。。。。。。。。");
        if (StrUtil.isEmpty(uploadFileData.getObjectName())) {
            throw new CustomFileException(OssEnum.FILE_FAIL_OBJECTNAME_NOT_EXIST);
        }

        try {
            String objectName = uploadFileData.getObjectName();
            String var1 = (bucket + "/" + objectName).replace("//", "/");
            File ff = new File(var1);
            // 上传文件
            FileUtil.writeFromStream(uploadFileData.getFileStream(), ff);

            return UploadRespDTO.builder().bucket(bucket).objectName(objectName).build();
        } catch (Exception e) {
            log.error("文件上传失败：{}", e);
            throw new CustomFileException(OssEnum.FILE_FAIL_UPLOAD);
        }
    }

    @Override
    public DownloadRespDTO get(String objectName) {
        String var1 = (bucket + "/" + objectName).replace("//", "/");
        File ff = new File(var1);

        try (InputStream ipt = new FileInputStream(ff)) {
            byte[] bytes = IoUtil.readBytes(ipt);

            return DownloadRespDTO.builder().bytes(bytes).build();
        } catch (IOException e) {
            throw new CustomFileException(OssEnum.FILE_FAIL_DOWNLOAD);
        }
    }
}
